import logging
import time
import json

from tornado.web import RequestHandler
from tornado.web import asynchronous
from tornado.gen import coroutine
from tornado.web import authenticated

from handlers import BaseHandler, AuthHandler
from urllib.parse import urlencode
from util.function import hash


class AdminBaseHandler(AuthHandler):

    def prepare(self):

        if not self.current_user or (type(self.current_user) is not dict) or self.current_user['username'] == None:
            url = self.get_login_url()
            if "?" not in url:
                url += "?" + urlencode(dict(next=self.request.full_url()))
            self.redirect(url)
        elif self.current_user['power'] != 20:
            self.redirect("/")

        super(AdminBaseHandler, self).prepare()

    def get_login_url(self):
        return u"/admin/signin"


class IndexHandler(AdminBaseHandler):

    @coroutine
    def get(self):

        limit = {'title': 1, 'from': 1, 'dtype': 1,
                 'updatetime': 1, 'status': 1}

        data_standby_cur = self.db.dataset.find(
            {"status": {"$in": [0, 10]}}, limit)
        data_standby = yield data_standby_cur.to_list(5)

        apply_limit = {'reseach.title': 1, 'user': 1, 'dataset.title': 1}
        apply_cur = self.db.apply.find({"status": {"$ne": -10}}, apply_limit)
        applys = yield apply_cur.to_list(5)

        self.render('admin/home.html',
                    data_standby=data_standby, applys=applys)


class SigninHandler(BaseHandler):

    def get(self):
        self.render('admin/signin.html')

    @coroutine
    def post(self):
        username = self.get_body_argument('username', default="")
        password = self.get_body_argument('password', default="")
        remember = self.get_body_argument('remember', default="off")

        user = yield self.db.member.find_one({"username": username})
        if not user:
            self.results['error'] = '用户不存在'
            self.render('admin/signin.html')

        check = yield self.backend.submit(hash.verify, password, user['password'])

        if not check:
            self.results['error'] = '密码错误'
            self.render('admin/signin.html')

        session = self.set_session(user)

        if remember == "on":
            cookie_json = json.dumps(session)
            self.set_secure_cookie(
                "user_info", cookie_json, expires_days=30, httponly=True)

        yield self.db.member.find_and_modify({"username": username}, {
            "$set": {
                "logintime": time.time(),
                "loginip": self.get_ipaddress()
            }
        })
        self.redirect("/admin")


class SignoutHandler(BaseHandler):

    def get(self):

        self.session.delete('current_user')

        self.redirect(self.get_argument("next", "/admin/signin"))
